package com.yun.zf.admin.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.admin.mapper.SysRateDiscountMapper;
import com.yun.zf.admin.service.SysRateDiscountService;
import com.yun.zf.common.app.domain.SysRateDiscount;
import com.yun.zf.common.admin.model.pact.RateDiscountMo;
import com.yun.zf.common.mapstruct.admin.PactMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 佣金折扣表 服务实现类
 * </p>
 *
 * @author cj
 * @since 2021-04-15
 */
@Service
@Slf4j
public class SysRateDiscountServiceImpl extends ServiceImpl<SysRateDiscountMapper, SysRateDiscount> implements SysRateDiscountService {

    /**
     * 获取城市折扣系数
     * @param provCode
     * @param cityCode
     * @param type
     * @param communityId
     * @return
     */
    @Override
    public   List<RateDiscountMo> getDiscount(Long provCode, Long cityCode, String type, Long communityId) {
        String nowDate =DateUtil.format(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss");
        QueryWrapper<SysRateDiscount> discountQueryWrapper = new QueryWrapper<>();
        discountQueryWrapper = discountQueryWrapper.select("d_value","money_type").eq("province_code", provCode).eq("city_code", cityCode)
                .eq("status", 0).apply("UNIX_TIMESTAMP(start_date) <= UNIX_TIMESTAMP('" + nowDate + "')").apply("UNIX_TIMESTAMP(end_date) >= UNIX_TIMESTAMP('" + nowDate + "')").eq("type", Integer.parseInt(type));
        if ( communityId!=null&&communityId > 0L) {
            discountQueryWrapper.eq("community_id", communityId);
        }
        discountQueryWrapper.orderByAsc("sort");
        List<SysRateDiscount> discounts = baseMapper.selectList(discountQueryWrapper);
        if (discounts.size() > 0) {
       List<RateDiscountMo> rateDiscountMos =   PactMapper.INSTANCE.rateToMo(discounts);
            log.info("城市 {} 折扣系数为 {} ",cityCode, JSON.toJSONString(rateDiscountMos));
            return rateDiscountMos;
        }
        return null;
    }
}
